package com.liu.activiti.config;

import com.liu.activiti.mapper.ActReDeploymentConfigMapper;
import com.liu.activiti.pojo.activiti.ActReDeploymentConfig;
import com.liu.activiti.pojo.activiti.CustomDeployment;
import com.liu.activiti.service.ActivitiCoreService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.util.CollectionUtil;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

//@Component
@Slf4j
public class ActivitiStart implements InitializingBean {

    @Resource
    private ActReDeploymentConfigMapper actReDeploymentConfigMapper;

//    @Autowired
    private ActivitiCoreService activitiCoreService;

//    @Autowired
    private RepositoryService repositoryService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void afterPropertiesSet() {
        log.info("启动时部署工作流文件入口开始");
        ActReDeploymentConfig select = new ActReDeploymentConfig();
        select.setState("1");
        final List<ActReDeploymentConfig> actReDeploymentConfigs = actReDeploymentConfigMapper.listAll(select);
        if(CollectionUtil.isEmpty(actReDeploymentConfigs)) {
            log.info("没有需要部署的工作流文件");
            return;
        }
        for (ActReDeploymentConfig actReDeploymentConfig: actReDeploymentConfigs) {
            log.info("部署信息：actReDeploymentConfig{}", actReDeploymentConfig);
            final CustomDeployment customDeployment = activitiCoreService.deployByXmlFile(actReDeploymentConfig.getPath(), actReDeploymentConfig.getName());
            ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
            //添加查询条件，KEY
            query.deploymentId(customDeployment.getId());
            query.latestVersion();
            ProcessDefinition definition = query.singleResult();
            //获取流程定义id
            ActReDeploymentConfig actReDeployment = new ActReDeploymentConfig();
            actReDeployment.setId(actReDeploymentConfig.getId());
            actReDeployment.setState("0");
            actReDeployment.setUpdateTime(new Date());
            actReDeployment.setDeploymentId(customDeployment.getId());
            actReDeployment.setProcdefVersion(definition.getVersion()+"");
            actReDeployment.setProcdefId(definition.getId());
            actReDeployment.setProcdefKey(definition.getKey());
            actReDeploymentConfigMapper.update(actReDeployment);
        }
        log.info("启动时部署工作流文件入口结束，共计部署{}个流程" , actReDeploymentConfigs.size());
    }
}

